<template>
    <div>
        <input ref="fileRef" type="file" @change="fileChange">
        <button @click="upload">上传</button>
    </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { ref } from 'vue'
import httpApi from '@/http';
import { createChunk, createMd5, getExtension } from '../utils/uploadUtils'
const nums = ref(0)
const files = ref(null)
const fileRef = ref(null)
const completedCount = ref(0)

const fileChange = () => {
    nums.value = 0
    if (fileRef.value?.files && fileRef.value?.files?.length > 0) files.value = fileRef.value?.files[0]
}

const upload = async () => {
    if (!files.value) {
        return console.log('请选择要上传的文件')
    }
    const chunkList = createChunk(files.value)
    const md5 = await createMd5(chunkList)
    const a = await httpApi.loginApi.yanzheng(md5, getExtension(files.value.name)).catch(err => {
        console.log(err)
    })
    // const { uploadedList, url } = await httpApi.loginApi.yanzheng(md5, getExtension(files.value.name))
    const uploadedList = a.data.uploadedList
    const url = a.data.url
    if (url) {
        console.log('文件上传成功')
        ElMessage({
            message: '文件上传成功', type: 'success'
        })
        return
    }
    console.log(uploadedList, 'uploadedList')
    // 获取需要上传的切片
    const needUploadList = []
    chunkList.forEach((file, index) => {
        console.log(file)
        const filename = `${md5}-${index}`
        if (uploadedList.indexOf(filename) === -1) {
            needUploadList.push({
                filename,
                file
            })
        }
    })
    console.log(needUploadList, 'needUploadList.length')
    // // 上传切片
    //  nums.value = (i + 1) / needUploadList.length * 100
    Promise.all(needUploadList.map((item, i) => {
        // console.log('需要上传的切片', item)
        const data = new FormData()
        data.append('file', item.file)
        data.append('filename', item.filename)
        data.append('fileMd5', md5)


        return httpApi.loginApi.shangchuan(data).then(() => {
            // // 计算并更新进度条的值
            completedCount.value++
            nums.value = (completedCount.value / needUploadList.length) * 100
            nums.value = Math.floor(nums.value >= 100 ? 100 : nums.value)
        }).catch(err => {
            console.log(err)
        })
    })).then(async (res) => {
        console.log('合并')
        // 全部上传成功，合并切片
        console.log(nums.value, 'nums.value')
        const { code } = await httpApi.loginApi.hebing(md5, getExtension(files.value?.name)).catch(err => {
            console.log(err)
        })
        if (code === 200) {
            console.log('文件上传成功')
            ElMessage({
                message: '文件上传成功', type: 'success'
            })
        }
    }).catch(err => {
        console.log(err)
    })
}
</script>

<style lang="scss" scoped></style>